package com.nativetalk.service.three.demand;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.category.TsNtCategoryIndex;
import com.nativetalk.bean.demand.TdNtDemand;
import com.nativetalk.bean.dict.TsNtDictDeatil;
import com.nativetalk.bean.dict.TsNtDictDemand;
import com.nativetalk.bean.teacher.TdNtTeacherRoundRegister;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.TdNtDemandDao;
import com.nativetalk.dao.TdNtTeacherDao;
import com.nativetalk.dto.CheckCourseCategoryDto;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 16/8/27.
 */
@Service
public class DemandServiceImpl implements DemandService {

    private static Logger logger = Logger.getLogger(DemandServiceImpl.class);
    @Resource
    private TdNtDemandDao tdNtDemandDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;

    @Override
    public RetInfo findDemanByMembId(int memb_id) {
        String logInfo = this.getClass().getName() + ":findDemanByMembId:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            int size = tdNtDemandDao.findTdNtDemand(memb_id);
            /**
             * 判断用户是否填写过需求
             */
            if (size > 0) {
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("已填写");
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("未填写");
                List<TsNtDictDemand> tsNtDictDemands = tdNtDemandDao.findDemandDetail();
                retInfo.setObj(tsNtDictDemands);
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    /**
     * 查询 推荐老师
     * 如果学生的需求中有托福（美国）、雅思（英国），则随机查询6位美国、英国老师，否则随机查询6位老师
     * <p>
     * v4.3 需求修改
     * 根据学生的兴趣推荐相关老师（老师标签和学生兴趣建立关联关系）
     *
     * @param memb_id
     * @param tdNtDemands
     * @return
     */
    @Override
    @Transactional
    public RetInfo demand(int memb_id, List<TdNtDemand> tdNtDemands) {
        String logInfo = this.getClass().getName() + ":findDemanByMembId:";
        // 类路径+方法名
        logger.info("====== begin ======");
        RetInfo retInfo = new RetInfo();
        try {
            int size = tdNtDemandDao.findTdNtDemand(memb_id);
            if (size > 0) {
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("已填写");
            } else {
                if (tdNtDemands != null & tdNtDemands.size() > 0) {
                    //1 保存学生选择的需求
                    for (int i = 0; i < tdNtDemands.size(); i++) {
                        TdNtDemand tdNtDemand = tdNtDemands.get(i);
                        tdNtDemand.setMemb_id(memb_id);
                        tdNtDemandDao.insertTdNtDemand(tdNtDemand);
                    }

                    //2 根据学生的需求，推荐对应的老师
                    List<TdNtTeacherRoundRegister> teachers = tdNtTeacherDao.findTdNtRecommendTeacherWithDemand(tdNtDemands);
                    logger.info("根据兴趣推荐的老师个数：" + (teachers == null ? 0 : teachers.size()));
                    // 如果根据学生的兴趣没有查询到相关老师，那么就随机选择6个老师
                    if (teachers == null || teachers.size() == 0) {
                        logger.info("根据学生的兴趣没有查询到相关老师，系统随机选择6个老师");
                        teachers = tdNtTeacherDao.findTdNtTeacherRoundRegister();
                    }
                    // 设置老师的国家和大学
                    Map<String, TsNtDictDeatil> tsNtDictDeatilsMap = (Map<String, TsNtDictDeatil>) MemcachedUtils.get(MemcachedKey.tsNtDictDeatilsMap);
                    for (int i = 0; i < teachers.size(); i++) {
                        if (teachers.get(i).getDict_id() != null) {
                            TsNtDictDeatil tsNtDictDeatil = tsNtDictDeatilsMap.get(teachers.get(i).getDict_id() + "");
                            teachers.get(i).setUniversity(tsNtDictDeatil.getCode_name());
                            teachers.get(i).setCountry(tsNtDictDeatilsMap.get(tsNtDictDeatil.getParent_id() + "").getCode_name());
                        } else {
                            TsNtDictDeatil tsNtDictDeatil = tsNtDictDeatilsMap.get("3");
                            teachers.get(i).setUniversity(tsNtDictDeatil.getCode_name());
                            teachers.get(i).setCountry(tsNtDictDeatilsMap.get(tsNtDictDeatil.getParent_id() + "").getCode_name());
                        }

                    }
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("成功");
                    retInfo.setObj(teachers);
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("请选择您的需求");
                    logger.info("请选择您的需求");
                }
            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("====== end ======");
        return retInfo;
    }

    public RetInfo checkCourseCategory(Integer memb_id) {
        // 类路径+方法名
        logger.info("====== begin ======");
        RetInfo retInfo = new RetInfo();
        try {
            int size = tdNtDemandDao.searchTrailCategory(memb_id);
            if (size > 0) {
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("已填写");
            } else {
                List<TsNtCategoryIndex> tsNtCategoryIndexParent = (List<TsNtCategoryIndex>) MemcachedUtils.get(MemcachedKey.tsNtCategoryIndexParent);
                List<CheckCourseCategoryDto> dtoList = new ArrayList<>();
                for (TsNtCategoryIndex cate : tsNtCategoryIndexParent) {
                    CheckCourseCategoryDto dto = new CheckCourseCategoryDto();
                    dto.setCate_id(cate.getCate_id());
                    dto.setCate_img(cate.getCate_img());
                    dto.setCate_name(cate.getCate_name());
                    dtoList.add(dto);
                }

                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("成功");
                retInfo.setObj(dtoList);
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("====== end ======");
        return retInfo;
    }

    /**
     * 立即体验：保存用户选择的体验课的分类id
     *
     * @param memb_id
     * @param cate_id
     */
    public void checkCourseCategoryTrail(Integer memb_id, Integer cate_id) {
        tdNtDemandDao.addCheckCourseCategoryTrail(memb_id, cate_id);
    }
}
